import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';

export interface MenuItem {
  id: string;
  name: string;
  path?: string;
  children?: MenuItem[];
  expanded?: boolean;
  icon?: string;
  active?: boolean;
}

interface ThemeConfig {
  mode: 'light' | 'dark';
  layout: 'side' | 'top';
  primaryColor: string;
}

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {
  // 顶部菜单数据
  topMenus: MenuItem[] = [
    { id: 'system', name: '系统管理' },
    { id: 'user', name: '用户管理' },
    { id: 'user1', name: '用户管理1' }
  ];

  // 修改为递归结构的侧边菜单数据
  sideMenusMap: { [key: string]: MenuItem[] } = {
    system: [
      { 
        id: 'systemManage', 
        name: '系统设置',
        expanded: true,
        icon: 'setting',
        children: [
          { id: 'role', name: '角色管理', path: '/main/role', icon: 'team' },
          { id: 'menu', name: '菜单管理', path: '/main/menu', icon: 'menu' }
        ]
      },
      {
        id: 'logManage',
        name: '日志管理',
        expanded: false,
        icon: 'file-text',
        children: [
          { id: 'operationLog', name: '操作日志', path: '/main/operation-log', icon: 'profile' },
          { id: 'loginLog', name: '登录日志', path: '/main/login-log', icon: 'login' }
        ]
      },
      {
        id: 'activeReminder',
        name: '活动提醒',
        path: '/main/activity-reminder',
        icon: 'bell'
      }
    ],
    user: [
      {
        id: 'userManage',
        name: '用户设置',
        children: [
          { id: 'userList', name: '用户列表', path: '/main/user-list' },
          { id: 'userGroup', name: '用户组管理', path: '/main/user-group' }
        ]
      }
    ],
    user1: [
      {
        id: 'userManage1',
        name: '用户设置1',
        path: '/main/user-list'
      }
    ]
  };

  currentTopMenu = 'system';
  currentSideMenus: MenuItem[] = [];
  openedTabs: MenuItem[] = [];
  currentTab: MenuItem | null = null;
  isCollapsed = false;  // 添加控制菜单展开收起的状态
  userName = 'Admin';  // 添加用户名属性

  isThemeDrawerVisible = false;
  themeConfig: ThemeConfig = {
    mode: 'light',
    layout: 'side',
    primaryColor: '#1890ff'
  };
  
  themeColors = [
    '#1890ff',
    '#f5222d',
    '#fa8c16',
    '#13c2c2',
    '#52c41a',
    '#722ed1'
  ];

  constructor(private router: Router, private message: NzMessageService) {}

  ngOnInit() {
    this.currentSideMenus = this.sideMenusMap[this.currentTopMenu];
    
    // 查找第一个叶子节点
    const findFirstLeaf = (items: MenuItem[]): MenuItem | null => {
      for (const item of items) {
        if (!item.children?.length) {
          return item;
        }
        if (item.children) {
          const leaf = findFirstLeaf(item.children);
          if (leaf) return leaf;
        }
      }
      return null;
    };

    // 自动触发第一个叶子节点
    const firstLeaf = findFirstLeaf(this.currentSideMenus);
    if (firstLeaf) {
      this.addTab(firstLeaf);
    }
  }

  // 切换顶部菜单
  switchTopMenu(menu: MenuItem) {
    // 如果已达到最大标签数，检查是否有当前模块的标签页
    if (this.openedTabs.length >= 6) {
      // 检查是否存在目标模块的标签页
      const hasTabInTargetModule = this.openedTabs.some(tab => 
        this.isTabInModule(tab, this.sideMenusMap[menu.id] || [])
      );

      // 如果没有当前模块的标签页，拦截切换并提示
      if (!hasTabInTargetModule) {
        this.message.warning('已达到最大标签数，请先关闭一些标签页！');
        return;
      }
    }

    // 继续原有的模块切换逻辑
    if (this.currentTopMenu !== menu.id) {
      this.currentTopMenu = menu.id;
      this.currentSideMenus = this.sideMenusMap[menu.id] || [];
      
      const onlyLeafNodes = this.currentSideMenus.every(item => !item.children?.length);
      if (onlyLeafNodes) {
        this.isCollapsed = true;
      } else {
        this.isCollapsed = false;
      }

      // 检查是否有当前模块的已打开标签页
      const existingTab = this.openedTabs.find(tab => 
        this.isTabInModule(tab, this.currentSideMenus)
      );

      // 如果有已打开的标签页，切换到该标签页
      if (existingTab) {
        this.switchTab(existingTab);
      } else {
        // 否则打开第一个叶子节点
        const firstLeaf = this.findFirstLeaf(this.currentSideMenus);
        if (firstLeaf) {
          this.onMenuItemClick(firstLeaf);
        }
      }
    }
  }

  // 检查是否是只有一个叶子节点的模块
  private isSingleLeafModule(items: MenuItem[]): boolean {
    // 如果只有一个菜单项且没有子节点，则为单叶子节点模块
    return items.length === 1 && !items[0].children?.length;
  }

  // 判断标签页是否属于指定的菜单列表
  private isTabInModule(tab: MenuItem, menuItems: MenuItem[]): boolean {
    const findInMenu = (items: MenuItem[]): boolean => {
      for (const item of items) {
        if (item.id === tab.id) return true;
        if (item.children?.length && findInMenu(item.children)) return true;
      }
      return false;
    };
    return findInMenu(menuItems);
  }

  // 添加新Tab
  addTab(item: MenuItem) {
    if (this.openedTabs.length >= 6) {
      this.message.warning('最多只能打开 6 个标签页！');
      return;
    }
    if (!this.openedTabs.find(tab => tab.id === item.id)) {
      this.openedTabs.push(item);
    }
    this.switchTab(item);
  }

  // 切换Tab
  switchTab(tab: MenuItem) {
    this.currentTab = tab;

    // 递归查找菜单项
    const findMenuItemParent = (items: MenuItem[], targetId: string, topMenuId: string): boolean => {
      for (const item of items) {
        if (item.id === targetId) {
          this.currentTopMenu = topMenuId;
          this.currentSideMenus = this.sideMenusMap[topMenuId];
          return true;
        }
        if (item.children?.length && findMenuItemParent(item.children, targetId, topMenuId)) {
          return true;
        }
      }
      return false;
    };

    // 在所有一级菜单中查找
    for (const [topMenuId, sideMenus] of Object.entries(this.sideMenusMap)) {
      if (findMenuItemParent(sideMenus, tab.id, topMenuId)) {
        break;
      }
    }

    if (tab.path) {
      this.router.navigate([tab.path]);
    }
  }

  // 关闭Tab
  closeTab(tab: MenuItem, event: Event) {
    event.stopPropagation();
    
    // 如果只剩一个tab，不允许关闭
    if (this.openedTabs.length <= 1) {
      return;
    }

    const index = this.openedTabs.indexOf(tab);
    this.openedTabs = this.openedTabs.filter(t => t.id !== tab.id);
    
    if (this.currentTab?.id === tab.id) {
      this.switchTab(this.openedTabs[Math.min(index, this.openedTabs.length - 1)]);
    }
  }

  // 处理菜单点击
  onMenuItemClick(item: MenuItem) {
    if (item.path) {  // 只有有path的菜单项才能打开tab
      // 检查是否已存在该标签页
      const existingTab = this.openedTabs.find(tab => tab.id === item.id);
      if (existingTab) {
        // 如果已存在，直接切换到该标签页
        this.switchTab(existingTab);
      } else if (this.openedTabs.length >= 6) {
        // 如果不存在且已达到最大标签数，显示提示
        this.message.warning('最多只能打开 6 个标签页！');
      } else {
        // 如果不存在且未达到最大标签数，添加新标签页
        this.addTab(item);
      }
    }
  }

  // 处理菜单展开/折叠
  onExpandChange(event: {id: string; expanded: boolean}) {
    // 递归查找并更新菜单项的expanded状态
    const updateExpanded = (items: MenuItem[], targetId: string, expanded: boolean): boolean => {
      for (const item of items) {
        if (item.id === targetId) {
          item.expanded = expanded;
          return true;
        }
        if (item.children?.length && updateExpanded(item.children, targetId, expanded)) {
          return true;
        }
      }
      return false;
    };

    // 更新所有菜单中的状态
    for (const menuItems of Object.values(this.sideMenusMap)) {
      if (updateExpanded(menuItems, event.id, event.expanded)) {
        break;
      }
    }
  }

  toggleSideMenu() {
    this.isCollapsed = !this.isCollapsed;
  }

  private findFirstLeaf(items: MenuItem[]): MenuItem | null {
    for (const item of items) {
      if (!item.children?.length) {
        return item;
      }
      if (item.children) {
        const leaf = this.findFirstLeaf(item.children);
        if (leaf) return leaf;
      }
    }
    return null;
  }

  private highlightLeftMenu(tab: MenuItem) {
    // 逻辑来反显左侧菜单
    this.currentSideMenus.forEach(item => {
      // 确保 MenuItem 有 active 属性
      if (item.hasOwnProperty('active')) {
        item.active = item.id === tab.id; // 设置当前选中的菜单项
      }
    });
  }

  logout() {
    // 这里添加退出逻辑
    this.router.navigate(['/login']);
  }

  openThemeDrawer() {
    this.isThemeDrawerVisible = true;
  }

  closeThemeDrawer() {
    this.isThemeDrawerVisible = false;
  }

  changeThemeColor(color: string) {
    this.themeConfig.primaryColor = color;
  }

  applyTheme() {
    // 应用主题配置
    document.body.classList.toggle('dark-theme', this.themeConfig.mode === 'dark');
    document.body.style.setProperty('--primary-color', this.themeConfig.primaryColor);
    // 保存配置到本地存储
    localStorage.setItem('themeConfig', JSON.stringify(this.themeConfig));
    this.closeThemeDrawer();
  }

  resetTheme() {
    this.themeConfig = {
      mode: 'light',
      layout: 'side',
      primaryColor: '#1890ff'
    };
    this.applyTheme();
  }
}
